package pool

import "sync"

const _MAX_RECYCLING_CAP = 4 << 10

// slicePointerPool 定义 *[]byte 复用池的类型
type slicePointerPool struct {
	// maxRecyclingCap 最大回收容量
	maxRecyclingCap int
	// pool 复用池
	pool *sync.Pool
}

// NewSlicePointerPool 创建一个 *[]byte 复用池
func NewSlicePointerPool(sliceCap int, maxRecyclingCap ...int) *slicePointerPool {
	_maxRecyclingCap := _MAX_RECYCLING_CAP
	if len(maxRecyclingCap) > 0 {
		_maxRecyclingCap = maxRecyclingCap[0]
	}

	return &slicePointerPool{
		maxRecyclingCap: _maxRecyclingCap,
		pool: &sync.Pool{
			New: func() any {
				buf := make([]byte, 0, sliceCap)
				return &buf
			},
		},
	}
}

// Alloc 分配一个 *[]byte 对象
func (own *slicePointerPool) Alloc() *[]byte {
	return own.pool.Get().(*[]byte)
}

// Dealloc 释放当前 *[]byte 对象
func (own *slicePointerPool) Dealloc(obj *[]byte) {
	// 为了减少峰值分配，只向池返回较小的缓冲区
	if cap(*obj) <= own.maxRecyclingCap {
		*obj = (*obj)[:0]
		own.pool.Put(obj)
	}
}
